#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   download_drive.py
@Time    :   2024/01/21 17:45:11
@Author  :   chakcy 
@Email   :   947105045@qq.com
@description   :   下载浏览器驱动
'''

import requests
import json
from rpa_tool.get_version import get_chrome_version
import urllib.request
import os
import zipfile  

# 获取当前环境参数：浏览器版本，操作系统
version_osname:dict = get_chrome_version()
# print(version_osname)

# 解压文件
def unzip_file(zip_filepath:str, dest_path:str) -> None:  
    with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:  
        zip_ref.extractall(dest_path)  

# 获取浏览器驱动下载入口
def get_chrome_driver(version:str) -> list:
    url= "https://registry.npmmirror.com/-/binary/chrome-for-testing/"
    try:
        response = requests.get(url)
    except:
        return None
    data = json.loads(response.text)
    driver_list = []
    for item in data:
        if '.'.join([i for i in item["name"].split(".")[:-1]]) == version:
            driver_list.append(item)
    return driver_list
   
# 获取浏览器驱动下载地址
def get_chrome_driver_url(version:str, os_name:str) -> None or str: # type: ignore
    """
    根据浏览器版本和操作系统获取对应的驱动下载地址

    Args:
        version (str): 浏览器版本
        os_name (str): 操作系统名称

    Returns:
        str or None: 返回驱动下载地址，如果获取失败则返回 None
    """
    driver_list = get_chrome_driver(version)
    if driver_list is not None:
        url = get_chrome_driver(version)[-1]['url']
    else:
        return None
    response = requests.get(url)
    data = json.loads(response.text)
    name = ""
    if os_name == "Linux":
        name = "linux64"
    elif os_name == "Windows":
        name = "win64"
    for item in data:
        if item['name'] == name+"/":
            response = requests.get(item['url'])
            for i in json.loads(response.text):
                if i['name'] == f"chromedriver-{name}.zip":
                    return i['url']

# 下载浏览器驱动
def download_chrome_driver(path:str) -> None or str: # type: ignore
    version = '.'.join([i for i in version_osname['version'].split(".")[:-1]])
    url = get_chrome_driver_url(version, version_osname["os_name"])
    if url is not None:
        os.path.exists(os.path.dirname(path)) or os.makedirs(os.path.dirname(path))
        req = urllib.request.urlopen(url)
        with open(path, "wb") as f:
            f.write(req.read())
        unzip_file(path, os.path.dirname(path))
        os.remove(path)
    else:
        return "Driver download failed"


if __name__ == "__main__":
    download_chrome_driver(f"../chromedriver/{version_osname['version']}/chromedriver.zip")
    